<?php

namespace app\airobot\controller;

use app\airobot\CommonLogic;
use app\airobot\model\OriginProduct;
use app\airobot\model\Product;
use think\admin\Controller;
use think\facade\Db;

/**
 * 超管系统-商品管理
 * Class Products
 * @package app\airobot\controller
 */
class Products extends Controller
{
    private $table = 'product';
    public $commonLogic;

    /**
     * 商品列表
     * @auth true
     */
    public function index()
    {
        $this->commonLogic = new CommonLogic();
        $this->title = '商品列表';
        $query = $this->_query($this->table);
        $where = [];
        if (!empty($_GET['brand'])) {
            $where['brand'] = $_GET['brand'];
        }
        if (!empty($_GET['name'])) {
            $query->like($_GET['name']);
        }
        $query->where($where);
        $query->order('id asc')->page();
    }

    protected function _index_page_filter(array &$data)
    {
        $this->commonLogic = new CommonLogic();
        $ImageUrl = CommonLogic::GetImageUrl();

        foreach ($data as &$vo) {
            $vo = $this->dealDecimal($vo);
            if (strlen($vo['description']) > 80) {
                $vo['description'] = $this->commonLogic->TruncateString($vo['description'], 80) . "...";
            }
            $vo['amount'] = $this->commonLogic->DealAmount($vo['amount']);
            $vo['image'] = $ImageUrl['product'] . $vo['image'];
        }
    }

    /**
     * 导出文件
     * @auth true
     */
    public function export()
    {
        // 获取数据
        $this->commonLogic = new CommonLogic();
        $list = Db::table('product')->select()->toArray();
        foreach ($list as &$vo) {
            // spin金额
            $vo = $this->dealDecimal($vo);
            // image
            $imageArr = explode("/", $vo['image']);
            $vo['image'] = end($imageArr);
        }

        // 设置 CSV 文件的名字
        $filename = "product.csv";
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '";');
        $output = fopen('php://output', 'w');

        // 写入 CSV 头部
        fputcsv($output, ['id', '品牌', '名称', '描述', '图片', '价格']);

        // 写入数据行
        foreach ($list as $k => $v) {
            fputcsv($output, [$v['id'], $v['brand'], $v['name'], $v['description'], $v['image'], $v['amount']]);
        }

        // 关闭输出流
        fclose($output);
    }

    public function dealDecimal($data)
    {
        foreach ($data as $key => $value) {
            if ($key == "amount") {
                $data[$key] = floatval($value);
            }
        }
        return $data;
    }

    /**
     * 添加数据字典
     * @auth true
     */
    public function add()
    {
        $this->checkCreateAndEdit(false);

        OriginProduct::mForm('form');
    }

    /**
     * 编辑数据字典
     * @auth true
     */
    public function edit()
    {
        $this->commonLogic = new CommonLogic();
        if ($this->request->isPost()) {
            $this->checkCreateAndEdit(true);
            $this->success("保存成功！");
        }

        $productModel = new \app\airobot\model\Product();
        $vo = $productModel->queryInfo(["id" => $_GET["id"]]);
        $vo = $this->dealDecimal($vo);
        $this->vo = $vo;
        OriginProduct::mForm('form');
    }

    public function checkCreateAndEdit($isUpdate = true)
    {
        if ($this->request->isPost()) {
            if ($_POST["brand"] == "") {
                $this->error("品牌错误！");
            }
            if ($_POST["name"] == "") {
                $this->error("名称错误！");
            }
            if ($_POST["description"] == "") {
                $this->error("描述错误！");
            }
            if ($_POST["image"] == "") {
                $this->error("盒子图片错误！");
            }
            if ($_POST["amount"] == "" || $_POST["amount"] < 0) {
                $this->error("开盒金额错误！");
            }
            $productModel = new Product();
            $productInfo = $productModel->queryInfo(["name" => $_POST["name"]]);
            if (!is_null($productInfo) && $productInfo["name"] != $_POST["name"]) {
                $this->error("存在相同名称的商品！");
            }

            if ($isUpdate) {
                $productModel = new \app\airobot\model\Product();
                $productModel->updateInfo(["id" => $_POST["id"]], $_POST);
            }
        }
    }

    /**
     * 删除
     * @auth true
     */
    public function remove()
    {
        if ($this->request->isPost()) {
            // 查询box
            $boxList = Db::table('box')->whereLike("product_ids", "%[" . $_POST["id"] . "]%")->select()->toArray();
            if (count($boxList) > 0) {
                $this->error("存在Box使用商品，请先删除对应的Box！");
            }

            // forge表
            $forgeModel = new \app\airobot\model\Forge();
            $forgeInfo = $forgeModel->queryInfo(['product_id' => $_POST["id"]]);
            if (!is_null($forgeInfo) && $forgeInfo["product_id"] == $_POST["id"]) {
                $this->error("存在Forge使用商品，请先删除对应的Forge！");
            }
        }
        $this->_delete($this->table, 'id');
    }
}